
package br.com.fiap.dao.impl;

import java.io.Serializable;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.Session;
import org.hibernate.ejb.HibernateEntityManager;

import br.com.fiap.dao.AbstractDAO;

public abstract class AbstractDAOImpl<T> implements AbstractDAO<T> {

	private static final long serialVersionUID = 1725509461365787006L;
	
	private EntityManager entityManager;
	
	public AbstractDAOImpl() {
		entityManager = this.createEntityManager();
	}
	
	public final T findById(final Serializable id) {
		Session session = this.getHibernateSession();
		T cliente = (T) session.get(getEntityClass(), id);
		
		session.clear();
		session.close();
		
		return cliente;
	}
	
	@Override
	public void saveOrUpdate(T entity) {

		Session session = this.getHibernateSession();
		
		session.beginTransaction();
		session.saveOrUpdate(entity);
		session.getTransaction().commit();
		session.close();
		
	}
	
	public final void delete(final T entity) {
		
		Session session = this.getHibernateSession();
		
		session.beginTransaction();
		session.delete(entity);
		session.getTransaction().commit();
		session.close();
		
	}
	
	public final void delete(final Serializable id) {
		Session session = this.getHibernateSession();
		
		session.beginTransaction();
		Object entity = session.get(this.getEntityClass(), id);
		session.delete(entity);
		session.getTransaction().commit();
		session.close();
	}
	
	protected final EntityManager getEntityManager() {
		
		if (this.entityManager == null) {
			this.entityManager = this.createEntityManager();
		}
		
		return this.entityManager;
	}
	
	protected final Session getHibernateSession() {

		EntityManager em = this.getEntityManager();
		
		HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
		
		if (!hem.getSession().isOpen()) {
			return hem.getSession().getSessionFactory().openSession();
		}
		
		return hem.getSession();
	}
	
	public abstract Class<T> getEntityClass();
	
	private EntityManager createEntityManager() {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("fiapAirportPU");
		
//		em.getTransaction().begin();
//		
//		Query createQuery = em.createQuery("select a from Assento a");
//		
//		createQuery.getSingleResult();
//
//		em.close();
//		emf.close();
		
		return emf.createEntityManager();
		
	}

}
